package com.wn.pettyloan.security.emp;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wn.pettyloan.security.JwtUtils;
import com.wn.pettyloan.security.RedisCache;
import com.wn.pettyloan.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @program: pettyloan
 * @ClassName EmpLoginAuthenticationSuccessHandler
 * @description:
 * @author: 韩旭
 * @create: 2022-12-15 14:26
 **/

@Slf4j
public class EmpLoginAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisCache redisCache;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

//存放authentication到SecurityContextHolder，后续security就能获取到当前登录的用户信息了
        SecurityContextHolder.getContext().setAuthentication(authentication);

        LoginEmp loginEmp = (LoginEmp) authentication.getPrincipal();
        // 生成token
        String token = jwtUtils.generateToken(loginEmp.getUsername());
        //把loginUser保存到redis中，七天后过期，减少每次请求对mysql的读操作
        redisCache.setCacheObject("rbac:" + loginEmp.getUsername(), loginEmp, 604800, TimeUnit.SECONDS);
        //User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        log.info("用户[" + authentication.getPrincipal() + "]登陆成功！");
        response.setContentType("application/json;charset=UTF-8");
        String string = new ObjectMapper().writeValueAsString(Result.ok().data("list", loginEmp.getMenuList()).data("token", token));
        response.getWriter().println(string);
    }

}